package com.goods.link.amazon;

import com.goods.link.bean.ExProduct;
import com.goods.link.bean.ResultExProduct;
import com.goods.link.bean.ResultStatus;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zhengjunbo on 2015/9/16.
 */
@Service
public class RequestAndExtractor {
    /**
     *
     * @param url
     * @return
     */
    public ResultExProduct getProduct(String url){
        ResultExProduct resultExProduct= new ResultExProduct();

        ExProduct exProduct = new ExProduct();
        resultExProduct.setExProduct(exProduct);

        Connection connect = Jsoup.connect(url);
        String referer ="http://www.amazon.com";
        Document parse = null;
        try {
            parse = connect.header("Referer", referer).userAgent(generateUserAgent()).timeout(10000).get();
        } catch (IOException e) {
            resultExProduct.setResultStatus(ResultStatus.TIME_OUT.getCode());
            e.printStackTrace();
            return resultExProduct;
        }

        try {
            String leibie = parse.select("#wayfinding-breadcrumbs_feature_div > ul").text();
            exProduct.setCategory(leibie);

            String text = parse.select("#productTitle,#title").first().text();
            exProduct.setTitle(text);


            String productId = findProdctId(parse.outerHtml());
            exProduct.setProductId(productId);

            String price = parse.select("#priceblock_ourprice").text();
            if (StringUtils.isEmpty(price)) {
                price = parse.select("#priceblock_saleprice").text();
            }
            if (StringUtils.isEmpty(price)) {
                price = parse.select("span.a-size-medium.a-color-price.a-text-bold").first().text();
            }

            System.out.println("price:" + price);
            exProduct.setPrice(price.split("-")[0].trim().substring(1).replaceAll(",", ""));
            Pattern pattern = Pattern.compile("('colorImages': )(\\{[\\s\\S]*?\\}\\]\\})(,)");
            Matcher matcher = pattern.matcher(parse.outerHtml());
            matcher.find();
            String jsonStr = matcher.group(2);
            JsonParser parser = new JsonParser();
            JsonObject jsonObject = parser.parse(jsonStr).getAsJsonObject();
            List<String> imageUrls = new ArrayList<>();
            for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
                for (JsonElement elem : entry.getValue().getAsJsonArray()) {

                    JsonObject object = elem.getAsJsonObject();

                    String imageUrl = null;
                    if (object.get("hiRes") != null && !object.get("hiRes").isJsonNull()) {

                        imageUrl = object.get("hiRes").getAsString();
                    } else if (object.get("large") != null && !object.get("large").isJsonNull()) {

                        imageUrl = object.get("large").getAsString();
                    }

                    if (StringUtils.isBlank(imageUrl)) {
                        continue;
                    }
                    imageUrls.add(imageUrl);
                    System.out.println("image:" + imageUrl);
                }
            }
            exProduct.setImageUrl(imageUrls);
        } catch (Exception e){
            e.printStackTrace();
            resultExProduct.setResultStatus(ResultStatus.OTHER_ERROR.getCode());
            return resultExProduct;
        }

        resultExProduct.setResultStatus(ResultStatus.SUCCESS.getCode());
        return resultExProduct;
    }

    private String findProdctId(String html) {
        Pattern pattern1 = Pattern.compile("(\"data\":)(\\{[\\s\\S]*?\\})(,\"loadingBarHtml\")");
        Matcher matcher1 = pattern1.matcher(html);
        Pattern pattern2 = Pattern.compile("(var dataToReturn = )(\\{\"print[\\s\\S]*?\\})(;)");
        Matcher matcher2 = pattern2.matcher(html);
        Matcher matcher = null;
        if(matcher1.find()){
            matcher = matcher1;
        } else if(matcher2.find()){
            matcher = matcher2;
        }
        if(matcher==null){
            return null;
        }
        String jsonStr = matcher.group(2);
        JsonParser paser = new JsonParser();
        JsonObject jsonObject0 = paser.parse(jsonStr).getAsJsonObject();



        return jsonObject0.get("parent_asin").getAsString();
    }

    public static String generateUserAgent() {
        return "Mozilla/4." + RandomUtils.nextInt(1, 10)
                + " (Windows NT 6.1; WOW64) AppleWebKit/537." + RandomUtils.nextInt(12, 38) + " (KHTML, like Gecko) Chrome/" + RandomUtils.nextInt(11, 41)
                + ".0." + RandomUtils.nextInt(1101, 2232) + "." + RandomUtils.nextInt(101, 129) + " Safari/5" + RandomUtils.nextInt(10, 38) + "." + RandomUtils.nextInt(12, 36);
    }
}
